package cn.javaex.hgo.action.system.service.hgo_table_column_info;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.javaex.hgo.action.system.dao.hgo_table_column_info.IHgoTableColumnInfoDAO;
import cn.javaex.hgo.action.system.view.HgoTableColumnInfo;
import cn.javaex.hgo.config.constant.HgoErrorMsg;
import cn.javaex.hgo.config.exception.HgoException;

@Service("HgoTableColumnInfoService")
public class HgoTableColumnInfoService {
	
	@Autowired
	private IHgoTableColumnInfoDAO iHgoTableColumnInfoDAO;
	
	/**
	 * 查询表的字段
	 * @param tableId 表的主键
	 * @return
	 */
	public List<HgoTableColumnInfo> listByTableId(String tableId) {
		return iHgoTableColumnInfoDAO.listByTableId(tableId);
	}
	
	/**
	 * 根据主键，查询字段信息
	 * @param id
	 * @return
	 */
	public HgoTableColumnInfo selectById(String id) {
		return iHgoTableColumnInfoDAO.selectById(id);
	}

	/**
	 * 保存表信息
	 * @param hgoTableColumnInfo
	 * @throws HgoException
	 */
	public void save(HgoTableColumnInfo hgoTableColumnInfo) throws HgoException {
		// 1.0 校验字段名是否重复
		int count = iHgoTableColumnInfoDAO.countByColumnName(hgoTableColumnInfo.getTableId(), hgoTableColumnInfo.getColumnName(), hgoTableColumnInfo.getId());
		if (count>0) {
			throw new HgoException(HgoErrorMsg.ERROR_200002);
		}
		
		Date now = new Date();
		hgoTableColumnInfo.setUpdateTime(now);
		if (hgoTableColumnInfo.getIsPrimaryKey()==null) {
			hgoTableColumnInfo.setIsPrimaryKey(0);
		}
		if (hgoTableColumnInfo.getPoint()==null) {
			hgoTableColumnInfo.setPoint(0);
		}
		if (StringUtils.isNotBlank(hgoTableColumnInfo.getRemark())) {
			hgoTableColumnInfo.setRemark(hgoTableColumnInfo.getRemark().replace("\r\n", "<br/>"));
		}
		
		// 2.0 新增或更新
		if (StringUtils.isEmpty(hgoTableColumnInfo.getId())) {
			// 新增
			hgoTableColumnInfo.setCreateTime(now);
			iHgoTableColumnInfoDAO.insert(hgoTableColumnInfo);
		} else {
			// 更新
			iHgoTableColumnInfoDAO.update(hgoTableColumnInfo);
		}
	}

	/**
	 * 删除字段
	 * @param id
	 */
	public void deleteById(String id) {
		iHgoTableColumnInfoDAO.deleteById(id);
	}

	/**
	 * 查询当前表下最大排序
	 * @param tableId 表主键
	 * @return
	 */
	public int selectMaxSortByTableId(String tableId) {
		int maxSort = 0;
		try {
			maxSort = iHgoTableColumnInfoDAO.selectMaxSortByTableId(tableId);
		} catch (Exception e) {
			
		}
		return maxSort;
	}

	/**
	 * 保存排序
	 * @param hgoTableColumnList
	 */
	public void saveSort(List<HgoTableColumnInfo> hgoTableColumnList) {
		for (HgoTableColumnInfo hgoTableColumnInfo : hgoTableColumnList) {
			iHgoTableColumnInfoDAO.update(hgoTableColumnInfo);
		}
	}

}